const Subscription = require('egg').Subscription;


class SendTicketSmsCache extends Subscription {

	static get schedule() {

		return {
			interval: '30s',
			type: 'worker',
			immediate: true,

			//disable: true,
		};
	}


	async subscribe() {

		const { ctx } = this;

		//ctx.app.logger.info('发送短信定时任务开始');

		const SMSToBeSentList = await ctx.service.order.SMSToBeSent();

		for(let i = 0; i < SMSToBeSentList.length; i++){
			const order = SMSToBeSentList[i];
			const mobile = order.mobile;
			const info = {
				title : order.sale_name,
				model : order.attr_name,
				num : order.num + '',
				code : order.order_unique_code, //+ ' ; ' + order.order_unique_code_url + ' ; ' + order.sms_diy,
				other : order.sms_diy,
				'order' : order.order_unique_code_url,
			};

			ctx.logger.info(info);

			let sentSmsState = 1;	//0:发送失败，1:发送成功
			let sentSmsFailMsg = '';
			let r = {};

			let content = '【香草科技】您已成功预定：' + info.title +
        	'，型号：' + info.model +
        	'，数量：' + info.num +
        	'，票码：' + info.code +
        	'，二维码：https://shop.hidlq.com/#/o/' + order.order_unique_code_url + 
        	'，说明：' + info.other + '。';

			try{
				r = await ctx.service.sms.send({mobile, info});
			}catch (err){
				ctx.logger.info('异常');
				sentSmsState = 0;
				sentSmsFailMsg = err.code;
				r = err.data;
			}

        	//console.log(r);
        	ctx.logger.info(r);
        	ctx.logger.info(content);
        	ctx.logger.info('字数：' + content.length);

        	const p = {
        		mobile, 
        		content, 
        		'requestid' : r.RequestId, 
        		'code' : r.Code, 
        		'message' : r.Message, 
        		'bizid' : r.BizId, 
        		'order_code' : order.order_code,
        		'state' : sentSmsState,
        		'failmsg' : sentSmsFailMsg,
        	};

        	const r2 = await ctx.service.sms.savelog(p);

        	//ctx.logger.info(r2);

        	const s = sentSmsState == 1 ? '2' : '3'; //2:成功,3:失败，
        	const r1 = await ctx.service.order.updateSmsState(order.order_code, s);

        	//失败也扣
        	//if(s == 3) return;

        	//扣服务费

        	//费用，每60个字0.1元。
        	const fee = content.length % 60 == 0 ?
        	parseInt(content.length / 60) : parseInt(content.length / 60) + 1;

    		const para = {
	            'fee' : fee * 10,
	            company_code : order.company_code,
	            type : '2', 
	            order_code : order.order_code,
	            remark : '【' + order.order_code + '】订单短信服务费用',
	            out_company_code : order.out_sale_company
	        };

	        const r3 = await ctx.service.serviceCharge.update(para);
	        if(!r3) ctx.logger.info('没有成功扣除短信费用。');
        		//const r3 = await ctx.service.serviceCharge.update(10, order.out_sale_company);

        	//ctx.logger.info(r1);
		}

		//ctx.app.logger.info('发送短信定时任务结束');

	}

}

module.exports = SendTicketSmsCache;